<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
        <el-form-item label="字典名称" prop="dictType">
          <el-select v-model="queryParams.dictType" class="width-120">
            <el-option v-for="item in typeOptions" :key="item.dictId" :label="item.dictName"
                       :value="item.dictType"/>
          </el-select>
        </el-form-item>
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="queryParams.dictLabel" clearable placeholder="请输入字典标签"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" class="width-120" clearable placeholder="数据状态">
            <el-option v-for="dict in dictDataMap['sys_normal_disable']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <div class="mr20" style="float: right">
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </div>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPerm="['system:dict:add']" :align="'center'" plain type="primary"
                   @click="handleAdd">
          <template #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPerm="['system:dict:edit']" :align="'center'" :disabled="single" plain type="success"
                   @click="handleUpdate">
          <template #icon>
            <i-ep-edit/>
          </template>
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPerm="['system:dict:remove']" :align="'center'" :disabled="multiple" plain type="danger"
                   @click="handleDelete">
          <template #icon>
            <i-ep-delete/>
          </template>
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPerm="['system:dict:export']" :align="'center'" plain type="warning"
                   @click="handleExport">
          <template #icon>
            <i-ep-download/>
          </template>
          导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button :align="'center'" plain type="warning" @click="handleClose">
          <template #icon>
            <i-ep-close/>
          </template>
          关闭
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive :border="true" :data="dataList" :header-cell-style="$headerCellStyle" :stripe='true'
              highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" type="selection" width="55"/>
      <el-table-column :align="'center'" label="字典编码" prop="dictCode"/>
      <el-table-column :align="'center'" label="字典标签" prop="dictLabel">
        <template #default="scope">
                    <span v-if="scope.row.listClass == '' || scope.row.listClass == 'default'">{{
                        scope.row.dictLabel
                      }}</span>
          <el-tag v-else :type="scope.row.listClass == 'primary' ? '' : scope.row.listClass">
            {{ scope.row.dictLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="字典键值" prop="dictValue"/>
      <el-table-column :align="'center'" label="字典排序" prop="dictSort"/>
      <el-table-column :align="'center'" label="状态" prop="status">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_normal_disable']" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="医保值" prop="medicalValue"/>
      <el-table-column :align="'center'" label="医保标签" prop="medicalLabel"/>
      <el-table-column :align="'center'" label="备注" prop="remark" show-overflow-tooltip/>
      <el-table-column :align="'center'" label="创建时间" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作">
        <template #default="scope">
          <el-button v-hasPerm="['system:dict:edit']" :align="'center'" type="success"
                     @click="handleUpdate(scope.row)">
            <template #icon>
              <i-ep-edit/>
            </template>
            修改
          </el-button>
          <el-button v-hasPerm="['system:dict:remove']" :align="'center'" type="danger"
                     @click="handleDelete(scope.row)">
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :total="total" @pagination="getList"/>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" :disabled="true"/>
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入数据标签"/>
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入数据键值"/>
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性"/>
        </el-form-item>
        <el-form-item label="排序" prop="dictSort">
          <el-input-number v-model="form.dictSort" :min="0" controls-position="right"/>
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option v-for="item in listClassOptions" :key="item.value"
                       :label="item.label + '(' + item.value + ')'" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dictDataMap['sys_normal_disable']" :key="dict.dictValue"
                      :value="dict.dictValue">{{
                dict.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="医保值" prop="medicalValue">
          <el-input v-model="form.medicalValue" placeholder="请输入医保值"/>
        </el-form-item>
        <el-form-item label="医保标签" prop="medicalLabel">
          <el-input v-model="form.medicalLabel" placeholder="请输入医保标签"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {addData, delData, getData, listData, updateData} from "@/api/system/dict/data";
import {getType, optionselect as getDictOptionselect} from "@/api/system/dict/type";
import {useDictStoreHook} from "@/store/modules/dict";
import {useRoute, useRouter} from 'vue-router';
import {useTagsViewStore} from '@/store/modules/tagsView'

const formRef = ref()
const useTagsView = useTagsViewStore()
const route = useRoute()
const router = useRouter()
const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('sys_normal_disable'))
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 字典表格数据
const dataList = ref([])
// 默认字典类型
const defaultDictType = ref("")
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 数据标签回显样式
const listClassOptions = ref([
  {
    value: "default",
    label: "默认"
  },
  {
    value: "primary",
    label: "主要"
  },
  {
    value: "success",
    label: "成功"
  },
  {
    value: "info",
    label: "信息"
  },
  {
    value: "warning",
    label: "警告"
  },
  {
    value: "danger",
    label: "危险"
  }
])

// 类型数据字典
const typeOptions = ref<any>([])
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  dictName: undefined,
  dictType: undefined,
  status: undefined
})
// 表单参数
const form = ref<any>({})
// 表单校验
const rules = ref({
  dictLabel: [
    {required: true, message: "数据标签不能为空", trigger: "blur"}
  ],
  dictValue: [
    {required: true, message: "数据键值不能为空", trigger: "blur"}
  ],
  dictSort: [
    {required: true, message: "数据顺序不能为空", trigger: "blur"}
  ]
})

const dictId = route.params && route.params.dictId;
getTypes(dictId);
getTypeList();

/** 查询字典类型详细 */
function getTypes(dictId) {
  getType(dictId).then(response => {
    queryParams.value.dictType = response.data.dictType;
    defaultDictType.value = response.data.dictType;
    getList();
  });
}

/** 查询字典类型列表 */
function getTypeList() {
  getDictOptionselect().then(response => {
    typeOptions.value = response.data;
  })
}

/** 查询字典数据列表 */
function getList() {
  listData(queryParams.value).then((response: any) => {
    dataList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dictCode: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    cssClass: undefined,
    listClass: 'default',
    dictSort: 0,
    status: "0",
    remark: undefined
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 返回按钮操作 */
function handleClose() {
  const obj = {path: "/system/dict"};
  // /system/dict-data
  useTagsView.delView(router.currentRoute).then((_res: any) => {
    router.push(obj)
  })
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  queryParams.value.dictType = defaultDictType.value;
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加字典数据";
  form.value.dictType = queryParams.value.dictType;
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.dictCode)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const dictCode = row.dictCode || ids.value
  getData(dictCode).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改字典数据";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.dictCode != undefined) {
        updateData(form.value).then(_response => {
          dictStore.removeDict(queryParams.value.dictType);
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addData(form.value).then(_response => {
          dictStore.removeDict(queryParams.value.dictType);
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const dictCodes = row.dictCode || ids.value;
  ElMessageBox.confirm('是否删除选中的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delData(dictCodes).then(() => {
      getList();
      ElMessage.success("删除成功");
      dictStore.removeDict(queryParams.value.dictType);
    })
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  // this.download('system/dict/data/export', {
  //     ...this.queryParams
  // }, `data_${new Date().getTime()}.xlsx`)
}
</script>


<script lang="ts">
export default {
  name: "DataInfo"
}
</script>
